package com.xander.myblog.interceptor;

import com.xander.myblog.VO.OwnerVO;
import com.xander.myblog.constant.Constants;
import com.xander.myblog.entity.Topic;
import com.xander.myblog.entity.User;
import com.xander.myblog.service.TopicService;
import com.xander.myblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author 叶振东
 * @date 2018-12-21
 */
@Component
public class SessionInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private UserService userService;

    @Autowired
    private TopicService topicService;

    String ownerString = "owner";

    String topicListString = "topicList";

    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
        HttpSession session=request.getSession();
        if (null == session.getAttribute(ownerString)) {
            User user = userService.getUserByPermission(Constants.BLOG_OWNER);
            OwnerVO owner = new OwnerVO();
            owner.setOwner(user.getNickname());
            owner.setDescription(user.getDescription());
            owner.setEmail(user.getEmail());
            owner.setGithub(user.getGithub());
            owner.setAvatar(user.getAvatar());
            if (null != user) {
                owner.setThemePrimary(user.getThemePrimary());
                owner.setThemeAccent(user.getThemeAccent());
                owner.setThemeLayout(user.getThemeLayout());
            } else {
                owner.setThemePrimary("teal");
                owner.setThemeAccent("teal");
                owner.setThemeLayout("light");
            }
            session.setAttribute(ownerString, owner);
        }
        if (null == session.getAttribute(topicListString)) {
            List<Topic> topicList = topicService.getExistTopic();
            session.setAttribute(topicListString, topicList);
        }
        return true;
    }
}
